﻿using System.Collections.Generic;
using Entitas;
using UnityEngine;

public class GraphSystem : IInitializeSystem
{
    private readonly IViewService _viewService;

    public GraphSystem(IViewService viewService)
    {
        _viewService = viewService;
    }

    public void Initialize()
    {
        Graph graph = new Graph(false);
        Vector2 spaceSize = new Vector2(GameDefine.WORLD_SIZEX, GameDefine.WORLD_SIZEZ);
        Vector2 center = spaceSize / 2;
        List<Vector3> nodes = new List<Vector3>();
        for (int y = 0; y < spaceSize.y + 1; y++)
        {
            for (int x = 0; x < spaceSize.x + 1; x++)
            {
                Vector3 p = new Vector3(x - center.x, 0, y - center.y);
                nodes.Add(p);
            }
        }

        int nextFreeNodeIndex = graph.GetNextFreeNodeIndex();
        foreach (var n in nodes)
        {
            GraphNode newNode = new GraphNode(nextFreeNodeIndex, n);
            nextFreeNodeIndex = graph.AddNode(newNode);
        }

        int rowCount = (int) spaceSize.x + 1;
        for (int y = 0; y < spaceSize.y + 1; y++)
        {
            for (int x = 0; x < spaceSize.x + 1; x++)
            {
                int nodeIndex = y * rowCount + x;

                if (y > 0)
                {
                    int downIndex = (y - 1) * rowCount + x;
                    graph.AddEdge(nodeIndex, downIndex);
                }

                if (x > 0 && y > 0)
                {
                    int leftDownIndex = (y - 1) * rowCount + x - 1;
                    graph.AddEdge(nodeIndex, leftDownIndex);
                }

                if (x > 0)
                {
                    int leftIndex = y * rowCount + x - 1;
                    graph.AddEdge(nodeIndex, leftIndex);
                }

                if (x > 0 && y < spaceSize.y)
                {
                    int leftUpIndex = (y + 1) * rowCount + x - 1;
                    graph.AddEdge(nodeIndex, leftUpIndex);
                }

                if (y < spaceSize.y)
                {
                    int upIndex = (y + 1) * rowCount + x;
                    graph.AddEdge(nodeIndex, upIndex);
                }

                if (x < spaceSize.x && y < spaceSize.y)
                {
                    int rightUpIndex = (y + 1) * rowCount + x + 1;
                    graph.AddEdge(nodeIndex, rightUpIndex);
                }

                if (x < spaceSize.x)
                {
                    int rightIndex = y * rowCount + x + 1;
                    graph.AddEdge(nodeIndex, rightIndex);
                }

                if (x < spaceSize.x && y > 0)
                {
                    int rightDownIndex = (y - 1) * rowCount + x + 1;
                    graph.AddEdge(nodeIndex, rightDownIndex);
                }
            }
        }

        Contexts.sharedInstance.game.SetGraph(graph);
        _viewService.CreateGraphView(Contexts.sharedInstance.game.graphEntity);
    }
}